package com.zzp.basepresenter.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.zzp.basepresenter.R;
import com.zzp.basepresenter.config.BaseConfig;
import com.zzp.basepresenter.ui.popwindows.BaseNoticePopWindow;
import com.zzp.basepresenter.ui.popwindows.LoadingProgressPopWindow;
import com.zzp.basepresenter.util.AppManager;
import com.zzp.basepresenter.util.ImmersiveStateUtil;
import com.zzp.basepresenter.util.LoggerUtils;
import com.zzp.basepresenter.util.SoftHideKeyBoardUtil;
import com.zzp.basepresenter.util.TextUtils;
import com.zzp.basepresenter.util.ToastUtils;

import java.util.Locale;


public abstract class BaseActivity extends AppCompatActivity {
    public Activity context;
    private long lastClickTime;
    private BaseNoticePopWindow baseNoticePopWindow;
    private LoadingProgressPopWindow loadingProgressPopWindow;

    public abstract int getContentView();

    public abstract boolean fitWindow();

    public abstract boolean softWindowAdjustPan();

    public abstract void init(Bundle savedInstanceState);

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.context = this;
//        changeLanguage(this, SharePreferenceUtils.getInstance(context).getString("CURRENT_LANGUAGE", "en"));
        AppManager.getAppManager().addActivity(this);
        if (!fitWindow()) {
            //所有布局布满全屏
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Window window = getWindow();
                window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                        | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                //更改状态栏背景色
                window.setStatusBarColor(Color.TRANSPARENT);
                //更改虚拟键背景色
                window.setNavigationBarColor(Color.BLACK);
            }
        } else {
            //沉浸式状态栏——界面上移遮挡状态栏，需设置根布局 android:fitsSystemWindows="true"
            ImmersiveStateUtil.setImmersiveState(this, R.color.white);
        }
        ImmersiveStateUtil.setStatusBarLightMode(this, true);
        if (getContentView() != 0) {
            setContentView(getContentView());
        }
        if (!softWindowAdjustPan()) {
            SoftHideKeyBoardUtil.assistActivity(this);
        }
        init(savedInstanceState);
    }

    /*
     *限制按钮多次点击一秒之内不能重复点击
     * */
    public boolean isSimpleClick() {
        long currentClickTime = System.currentTimeMillis();
        if ((currentClickTime - lastClickTime) >= BaseConfig.MIN_DELAY_TIME) {
            return true;
        }
        lastClickTime = currentClickTime;
        return false;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) { //Finger touch screen event
        if (ev.getAction() == MotionEvent.ACTION_DOWN) { // get current focus,Generally it is EditText
            View view = getCurrentFocus();
            if (isShouldHideSoftKeyBoard(view, ev)) {
                hideSoftKeyBoard(view.getWindowToken());
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    private boolean isShouldHideSoftKeyBoard(View view, MotionEvent event) {
        if (view != null && (view instanceof EditText)) {
            int[] l = {0, 0};
            view.getLocationInWindow(l);
            int left = l[0], top = l[1], bottom = top + view.getHeight(), right = left + view.getWidth();
            if (event.getX() > left && event.getX() < right && event.getY() > top && event.getY() < bottom) {
                // If click the EditText event ,ignore it return false;
                return false;
            } else {
                return true;
            }
        }
        // if the focus is EditText,ignore it;
        return false;
    }

    private void hideSoftKeyBoard(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    //全局提示
    public void showNoticeWindow(Activity context, String title, String message) {
        if (baseNoticePopWindow == null) {
            baseNoticePopWindow = BaseNoticePopWindow.getInstance(context);
        } else {
            if (baseNoticePopWindow.isShowing()) {
                baseNoticePopWindow.dismiss();
            }
        }
        baseNoticePopWindow.show(context, context.getWindow().getDecorView());
        if (!TextUtils.getInstance().isEmpty(title)) {
            baseNoticePopWindow.setTitle(title);
        }
        baseNoticePopWindow.setMessage(message);
        baseNoticePopWindow.setOnClickListener(new BaseNoticePopWindow.OnClickListener() {
            @Override
            public void onClick() {
                onButtonClickCallback();
            }
        });
    }

    //按钮回调
    public void onButtonClickCallback() {

    }

    //加载动画显示
    public void showLoading(Activity context) {
        if (loadingProgressPopWindow == null) {
            loadingProgressPopWindow = LoadingProgressPopWindow.getInstance(context);
        } else {
            if (loadingProgressPopWindow.isShowing()) {
                loadingProgressPopWindow.dismiss();
            }
        }
        loadingProgressPopWindow.show(context, context.getWindow().getDecorView());
    }

    //加载动画隐藏
    public void hideLoading() {
        if (loadingProgressPopWindow != null) {
            if (loadingProgressPopWindow.isShowing()) {
                loadingProgressPopWindow.dismiss();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (loadingProgressPopWindow != null) {
            if (loadingProgressPopWindow.isShowing()) {
                loadingProgressPopWindow.dismiss();
            }
        }
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        LoggerUtils.getInstance().i("activity onConfigurationChanged");
        context = this;
    }

    @Override
    protected void onStart() {
        super.onStart();
//        changeLanguage(this, SharePreferenceUtils.getInstance(context).getString("CURRENT_LANGUAGE", "en"));
    }

    public void changeLanguage(Context context, String languageId) {
        if (com.zzp.basepresenter.util.TextUtils.getInstance().isEmpty(languageId)) {
            return;
        }
        Locale locale = null;
        if (languageId.equals("en")) {
            locale = new Locale(languageId, Locale.ENGLISH.getCountry());
        } else if (languageId.equals("ko")) {
            locale = new Locale(languageId, Locale.KOREA.getCountry());
        } else if (languageId.equals("zh")) {
            locale = new Locale(languageId, Locale.CHINA.getCountry());
        }
        Resources resources = context.getResources();
        DisplayMetrics metrics = resources.getDisplayMetrics();
        Configuration configuration = resources.getConfiguration();
        configuration.fontScale = 1;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            configuration.setLocale(locale);
        } else {
            configuration.locale = locale;
        }
        resources.updateConfiguration(configuration, metrics);
    }

    public void showToast(String s) {
        ToastUtils.getInstance().ShortToast(context, s);
    }

    public void showToast(int res) {
        ToastUtils.getInstance().ShortToast(context, res);
    }
}